package com.soulless.array;

/**
 * @author zenglei
 * @Description 功能描述    冒泡排序
 * 1. 比较两个相邻对象
 * 2. 如果左边的大于右边，则调换位置
 * 3. 向右移动一个位置，比较接下来的两个对象
 * @date 2020/11/24 20:00
 */
public class BubbleSort {

    private long[] arr;
    private int length;

    public BubbleSort(int length) {
        this.arr = new long[length];
    }

    public void insert(long value) {
        this.arr[length] = value;
        this.length++;
    }

    public void display() {
        for (int i = 0; i < this.arr.length; i++) {
            System.out.print(this.arr[i] + " ");
        }
        System.out.print("\n");
    }

    public void bubbleSort() {
        for (int i = arr.length - 1; i > 1; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j+1]) swap(j, j+1);
            }
        }
    }

    private void swap(int one, int two) {
        long temp = arr[one];
        arr[one] = arr[two];
        arr[two] = temp;
    }

}

class TestBubbleSort {
    public static void main(String[] args) {
        BubbleSort bs = new BubbleSort(5);
        for (int i = 0; i < 5; i++) {
            long r = (long) (Math.random()*100);
            bs.insert(r);
        }
        bs.display();
        bs.bubbleSort();
        bs.display();
    }
}
